package back_0417;

import busuanzi.util.Logs;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * Auth: bruce-sha
 * Date: 2015/3/6
 */
public class HttpServer {

    public void start(final int port) throws Exception {

        try (AutoNioEventLoopGroup bossGroup = new AutoNioEventLoopGroup();
             AutoNioEventLoopGroup workerGroup = new AutoNioEventLoopGroup()) {

            ServerBootstrap bootstrap = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            pipeline.addLast(new HttpServerCodec());
//                            pipeline.addLast(new HttpResponseEncoder());
//                            pipeline.addLast(new HttpRequestDecoder());

//                            ch.pipeline().addLast(new ChunkedWriteHandler());
//                            ch.pipeline().addLast(new FileServerHandler());
                            pipeline.addLast(new ChunkedWriteHandler());
//                            pipeline.addLast(new HttpServerInboundHandler());
                            //用于写一个ChunkedInput
//                            ch.pipeline().addLast(new WriteStreamHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            Channel channel = bootstrap.bind(port).sync().channel();

            Logs.log("service started on port {}", port);

            channel.closeFuture().sync();
        }
    }

    class AutoNioEventLoopGroup extends NioEventLoopGroup implements AutoCloseable {

        public AutoNioEventLoopGroup() {
            super(Runtime.getRuntime().availableProcessors());
        }

        @Override
        public void close() throws Exception {
            shutdownGracefully();
        }
    }
}